#!/bin/bash

function helpMessage(){
    echo "SYNOPSIS"
    echo "    ./prepare.sh -t <Debug | Release> -l <artifactory url>"
    echo "OPTIONS"
    echo "    -h: show help for prepare.sh"
    echo "    -t: specified build type, alternative Debug and Release"
    echo "    -l: specified artifactory url, like Nexus or JFrog repo-url"
}

CURDIR=$(cd $(dirname $0); pwd)
while getopts "ht:l:" opt; do
    case $opt in
    t)
        if [ "$OPTARG" != "Debug" ] && [ "$OPTARG" != "Release" ]; then
            echo "build type only alternative debug and release"
            exit 1
        fi
        BUILD_TYPE="$OPTARG"
        ;;
    l)
        ARTIFACTORY_URL="$OPTARG"
        ;;
    h)
        helpMessage
        exit 0
        ;;
    ?)
        echo "    There is unrecognized parameter!"
        helpMessage
        exit 1
        ;;
    esac
done

artifact_exist=`conan remote list | grep artifact | awk '{print $2}'`
if [ ! -n "$BUILD_TYPE" ]; then
    BUILD_TYPE="Release"
fi
if [ ! -n "$ARTIFACTORY_URL" ] && [ "$artifact_exist" = "" ]; then
    echo "please specify the artifact address!"
    exit 1
elif [ "$artifact_exist" = "" ]; then
    conan remote add artifact $ARTIFACTORY_URL
elif [ ! -n "$ARTIFACTORY_URL" ]; then
    ARTIFACTORY_URL=$artifact_exist
elif [ "$ARTIFACTORY_URL" != "$artifact_exist" ]; then
    conan remote remove artifact
    conan remote add artifact $ARTIFACTORY_URL
fi
if [ ! -d output/build/conan ]; then
    mkdir -p output/build/conan
fi

echo "##########################################################"
echo "type: $BUILD_TYPE"
echo "workspace: $CURDIR"
echo "artifact url: $ARTIFACTORY_URL"
echo "##########################################################"

conan install ./cmake --install-folder=./output/build/conan -s build_type=$BUILD_TYPE -r artifact
if [ $? -ne 0 ]; then
    echo "build dependency error, please check 'cmake/conanfile.py' file or nexus-artifactory-server"
    exit 1
fi
